package com.gator.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author PABLO
 * @Date 2022/6/7 22:38
 * @Desc
 */
public class DelayedMessageProducer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("DelayedMsgGroup");
        producer.setNamesrvAddr("localhost:9876");
        producer.start();
        //批量发送
        List<Message> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {

            Message message = new Message("JGDK", ("hello" + i).getBytes(StandardCharsets.UTF_8));
            //message.setDelayTimeLevel(3);
            list.add(message);
        }
        producer.send(list);
        System.out.println("消息发送完毕");
    }
}

@Slf4j
class DelayedMessageConsumer {
    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("DelayedConsumerMsgGroup");
        consumer.setNamesrvAddr("localhost:9876");

        //*指定订阅的tag
        consumer.subscribe("JGDK", "*");
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                try {
                    for (MessageExt item : msgs
                    ) {
                        java.lang.String topic = item.getTopic();
                        java.lang.String msg = new java.lang.String(item.getBody(), "UTF-8");
                        java.lang.String tags = item.getTags();
                        log.info("收到延迟消息{}，tag是：{}，topic是：{}", msg, tags, topic);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();
    }
}
